package xyz.bali16.application.security.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.mapper.UserMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import xyz.bali16.application.model.user.UserDetailsModel;

/**
 * @author bali2 on 15/4/2023.
 * @version 1.0
 */
@Component
public class CustomTokenEnhancer implements TokenEnhancer {
    @Autowired
    private UserMapper userMapper;


    @Override
    public org.springframework.security.oauth2.common.OAuth2AccessToken enhance(org.springframework.security.oauth2.common.OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> additionalInformation = new HashMap<>();
        // 客户端
        String clientId = oAuth2Authentication.getOAuth2Request().getClientId();// 客户端ID
        Set<String> resourceIds = oAuth2Authentication.getOAuth2Request().getResourceIds(); // 资源集合
        // 用户
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        UserDetailsModel principal = (UserDetailsModel) userAuthentication.getPrincipal();
        //System.out.println("principal!"+principal);
        User user = userMapper.getUserByUsername(principal.getUsername());
        additionalInformation.put("userId", user.getUserId());
        additionalInformation.put("name", user.getName());
        additionalInformation.put("phone", user.getPhone());
        additionalInformation.put("email", user.getEmail());
        additionalInformation.put("username", user.getUsername());
        additionalInformation.put("status", user.getStatus());
        additionalInformation.put("deleted", user.getDeleted());
        additionalInformation.put("locked", user.getLocked());
        additionalInformation.put("createUser", user.getCreateUser());
        additionalInformation.put("gmtCreated", user.getGmtCreated());
        additionalInformation.put("gmtModified", user.getGmtModified());
        additionalInformation.put("avatar", user.getAvatar());
        additionalInformation.put("lastLoginIp", user.getLastLoginIp());
        additionalInformation.put("lastGmtLoginTime", user.getLastGmtLoginTime());
        // 2.设置到accessToken中
        additionalInformation.put("resourceIds", resourceIds);
        additionalInformation.put("clientId", clientId);
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInformation);
        return oAuth2AccessToken;
    }
}
